package com.FH.organization.meeting_record;

import com.FH.organization.Attachment.AttachmentResource;
import com.FH.organization.department.DepartmentResource;
import com.FH.organization.operator_log.OperatorLogPullDTO;
import com.FH.organization.operator_log.OperatorLogResource;
import com.FH.organization.people.KamMemberResource;
import com.FH.organization.suggestion.SuggestionResource;
import com.FH.organization.work_flow.WorkFlowResource;
import com.FH.util.AccessDB;
import com.FH.util.FileProcess;
import com.FH.util.ResultDTO;
import com.FH.util.warnSrc;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.Stateless;
import javax.inject.Inject;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/12/16.
 */
@Stateless
public class MeetingRecorderImpl extends AccessDB implements MeetingRcordDTO {
    @Inject
    KamMemberResource kamMemberResource;
    @Inject
    OperatorLogResource operatorLogResource;
    @Inject
    DepartmentResource departmentResource;
    @Inject
    WorkFlowResource workFlowResource;
    @Inject
    AttachmentResource attachmentResource;
    @Inject
    SuggestionResource suggestionResource;

    @Override
    public ResultDTO getMeetingRcordInfo(String serach, String page, String size) {
        ResultDTO resultDTO = new ResultDTO();

        try {
            JSONObject json = new JSONObject(serach);
            String existName = "0";

            String sqlexit = "select count(1) from meeting_record where 1=1 ";

            String sql_w = "";//查询条件sql组合
            String sql_page = "";//分页组合

            Integer page_ok = Integer.parseInt(page);//将定义page、size的String类型转换成Integer类型
            Integer size_ok = Integer.parseInt(size);

            if (page.equals("1")) {
                sql_page = " limit 0," + size + "";
            } else {
                sql_page = " limit " + ((page_ok - 1) * size_ok + 1) + "," + size + "";
            }

            if (json.has("member_id")) {
                sql_w += " AND member_id = '" + json.getString("member_id") + "'";
            }
            if (json.has("meeting_record_id")) {
                sql_w += " AND meeting_record_id = '" + json.getString("meeting_record_id") + "'";
            }

            String sql_ok = sqlexit + sql_w + sql_page;//组合好的sql语句
            existName = getReportingToOne(sql_ok);

            List<String[]> seresult = new ArrayList<String[]>();

            List<MeetingRecordShowlDTO> result = new ArrayList<MeetingRecordShowlDTO>();

            if (!existName.equals("0")) {
                String sqlq = "select meeting_record_id,meeting_name,meeting_time,meeting_short_desc,meeting_desc,member_id FROM meeting_record where 1=1  " + sql_w + " ORDER BY create_time DESC" + sql_page;

                seresult = this.getReportingTo(sqlq);

                //构建返回对象
                for (int i = 0; i < seresult.size(); i++) {


                    MeetingRecordShowlDTO meetingRecordShowlDTO = new MeetingRecordShowlDTO();

                    meetingRecordShowlDTO.setMeeting_record_id(seresult.get(i)[1]);
                    meetingRecordShowlDTO.setMeeting_name(seresult.get(i)[2]);
                    meetingRecordShowlDTO.setMeeting_time(seresult.get(i)[3]);
                    meetingRecordShowlDTO.setMeeting_short_desc(seresult.get(i)[4]);
                    meetingRecordShowlDTO.setMeeting_desc(seresult.get(i)[5]);
                    meetingRecordShowlDTO.setMember_id(seresult.get(i)[6]);
//                    ResultDTO jsonpeople = null, organization = null, attach = null, suggestion = null;
//                    if (null != seresult.get(i)[5] && !"".equals(seresult.get(i)[5])) {
//                        jsonpeople = kamMemberResource.getUserListInfo("{member_id:" + seresult.get(i)[5] + "}", "1", "1");
//
//                        textRcorderShowDTO.setMens(jsonpeople.getValues());
//                    }
//
//                    if (null != seresult.get(i)[4] && !"".equals(seresult.get(i)[4])) {
//                        organization = departmentResource.getDepartmentInfo("{organization_id:" + seresult.get(i)[4] + "}", "1", "1");
//                        textRcorderShowDTO.setDepartments(organization.getValues());
//                    }
//
//                    if (!seresult.get(i)[7].equals("") && seresult.get(i)[7] != null) {
//                        attach = attachmentResource.getAttachmentInfo("{attachment_id:" + seresult.get(i)[7] + "}", "1", "1");
//                        textRcorderShowDTO.setAttachmentInfo(attach.getValues());
//                    }
//                    if (seresult.get(i)[1] != null && !seresult.get(i)[1].equals("")) {
//
//                        suggestion = suggestionResource.getSuggestionInfo("{form_id:" + seresult.get(i)[1] + "}", "1", "1");
//                        textRcorderShowDTO.setSuggestionShowDTOs(suggestion.getValues());
//                    }
                    result.add(meetingRecordShowlDTO);

                }
            }
            if (seresult.size() != 0) {
                resultDTO.setStr(result.size() + "");
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.get_success);
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }
            resultDTO.setValues(result);

        } catch (JSONException e) {
            e.printStackTrace();

        }
        return resultDTO;
    }

    @Override
    public ResultDTO addMeetingRcordInfo(MeetingRecordPullDTO meetingRecordPullDTO) {
        ResultDTO resultDTO = new ResultDTO();//构建返回对象


        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        String existName = "";
        String meeting_record_id = meetingRecordPullDTO.getMeeting_record_id();
        if (meeting_record_id != null && !meeting_record_id.equals("")) {

            String sql = "select count(1) from meeting_record where meeting_record_id='" + meeting_record_id + "'";

            existName = getReportingToOne(sql);

            if (!existName.equals("0")) {
                return updateMeetingRcordInfo(meetingRecordPullDTO);
            }
        }


        if (null != meetingRecordPullDTO.getMeeting_desc() && !"".equals(meetingRecordPullDTO.getMeeting_desc())) {
            String html = replaceimage(meetingRecordPullDTO);
            meetingRecordPullDTO.setMeeting_desc(html);
        }


        String QUERY = "";

        //表中查看时间设为空值
        QUERY += "insert into meeting_record(meeting_record_id,meeting_name,meeting_time,meeting_short_desc,meeting_desc,member_id,create_time) values" +
                " ('" + uuid + "','" + meetingRecordPullDTO.getMeeting_name() + "','" + meetingRecordPullDTO.getMeeting_time() + "','" + meetingRecordPullDTO.getMeeting_short_desc()
                + "','" + meetingRecordPullDTO.getMeeting_desc() + "','" + meetingRecordPullDTO.getMember_id() + "','" + time + "')";
        int result = this.addReportingTo(QUERY);
        // 判断SQl是否执行成功
        if (result != 0) {
            resultDTO.setStr(uuid);
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.add_success);
            //日志操作
            OperatorLogPullDTO operatorlogPullDTO = new OperatorLogPullDTO();
            operatorlogPullDTO.setOperator_log_title("会议录入");
            operatorlogPullDTO.setOperator_log_content(meetingRecordPullDTO.getMeeting_name());
            operatorlogPullDTO.setMember_id(meetingRecordPullDTO.getMember_id());
            operatorLogResource.addOperatorLogInfo(operatorlogPullDTO);

//            //流程上报
//
//            WorkFlowPullDTO workFlowPullDTO = new WorkFlowPullDTO();
//            workFlowPullDTO.setWork_flow_formid(uuid);
//            workFlowPullDTO.setWork_flow_type("news_draft");
//            workFlowPullDTO.setWork_flow_desc("车辆申请请求审批");
//            workFlowPullDTO.setWork_flow_date(time);
//            workFlowPullDTO.setWork_flow_order("0");
//            workFlowPullDTO.setWork_flow_createid(textRcorderPullDTO.getMember_id());
//            workFlowPullDTO.setWork_flow_approval(textRcorderPullDTO.getReport_people());
//            workFlowPullDTO.setWork_flow_approval_organization_id(textRcorderPullDTO.getWork_flow_approval_organization_id());
//            workFlowPullDTO.setFlow_path_id("");
//            workFlowPullDTO.setWork_flow_suggestion("");
//            workFlowResource.addWorkFlowInfo(workFlowPullDTO);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }
        return resultDTO;
    }

    public String replaceimage(MeetingRecordPullDTO meetingRecordPullDTO) {
        String content = "<p><span>这是内容开始</span><br />"
                + "<img src=\"http://localhost:8080/uploadFile/video/1111111111.mp4\"/><br/>"
                + "<span>这是内容中间</span><br/>"
                + "<img src=\"http://localhost:8080/uploadFile/video/2222222222.mp4\"/><br/>"
                + "<span>这是内容结尾</span></p>";

        String regxpForEmbedTag = "<\\s*img\\s+([^>]*)\\s*>";
        Matcher matcher = Pattern.compile(regxpForEmbedTag).matcher(meetingRecordPullDTO.getMeeting_desc());
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String contentTemp = matcher.group(1);
            String contentTemp0 = matcher.group(0);
            String src = getImgStr(contentTemp0).get(0);
            String str[] = src.split(",");
            if (str != null && str.length > 1) {
                String filebase1 = str[1];
//                String filebase2[] = filebase1.split(",");
//                String filebase3 = filebase2[1];
                String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
                meetingRecordPullDTO.setFilestream(filebase1);
                meetingRecordPullDTO.setFile_type(uuid + ".jpg");
                meetingRecordPullDTO.setFile_name(uuid + ".jpg");
                String imagebase64 = getImage(meetingRecordPullDTO)[1];

                contentTemp = replaceContentByPartten(contentTemp,
                        "src=\"([^\"]+)\"", "src=\"" + imagebase64 + "\"");
                matcher.appendReplacement(sb, "<img " + contentTemp + ">");
                matcher.appendTail(sb);
            }
        }
        return !sb.toString().equals("") ? sb.toString() : meetingRecordPullDTO.getMeeting_desc();
    }

    /**
     * 得到网页中图片的地址
     */
    public static List<String> getImgStr(String htmlStr) {
        List<String> pics = new ArrayList<String>();
        String img = "";
        Pattern p_image;
        Matcher m_image;
        //     String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile
                (regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;
    }


    public static String replaceContentByPartten(String content, String partten, String target) {
        Matcher matcher = Pattern.compile(partten, Pattern.CASE_INSENSITIVE).matcher(content);
        if (matcher.find()) {
            StringBuffer temp = new StringBuffer();
            matcher.appendReplacement(temp, target);
            matcher.appendTail(temp);
            return temp.toString();
        } else {
            return content;
        }
    }

    /**
     * 保存图片方法
     *
     * @param
     * @return
     */
    public String[] getImage(MeetingRecordPullDTO meetingRecordPullDTO) {
        String str[] = new String[2];

        ResultDTO resultDTO = new ResultDTO();
        // TODO Auto-generated method stub
        String enpenform_image = "";
        //获取配置图片地址
        String[] image_path = this.getImage_path();
        String image_pathAddr = image_path[1];//服务器项目目录地址
        String image_pathSerAddr = image_path[2];//图片访问地址
        String imgDirct = image_pathAddr + "/notice";
        File f = new File(imgDirct);
        if (!f.exists()) {
            f.mkdirs();
            f.setWritable(true, false);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        String imgPath = imgDirct + "/" + meetingRecordPullDTO.getFile_type();


        //base64字符串保存为图片
        boolean headImg = FileProcess.GenerateImage(meetingRecordPullDTO.getFilestream(), imgPath);
        FileProcess.newlog("执行头像图片储存方法，储存照片地址：" + imgPath + " 方法返回：" + headImg);
        int resultls = 0;
        int mresult = 0;

        String imgurl = "/notice/" + meetingRecordPullDTO.getFile_type();

        //ArrayList<HeadPortaitDTO> result = new ArrayList<HeadPortaitDTO>();

        if (headImg) {
            //插入头像表
            enpenform_image += "insert into attachment(attachment_id,attachment_addr,head_portrait_time,file_type,file_name) values ('" + uuid + "','" + imgurl + "','" + df.format(new Date()) + "','" + meetingRecordPullDTO.getFile_type() + "','" + meetingRecordPullDTO.getFile_name() + "')";
            // enpenform_image += "insert into file(file_id,file_addr,file_time,filegui_id,file_name) values ('" + uuid + "','" +imgurl+ "','" +df.format(new Date()) + "','" + dataDTO.getFilegui_id() + "','" + dataDTO.getFiletype() + "')";
            //执行sql
            resultls = addReportingTo(enpenform_image);
        }

        if (resultls != 0) {
            str[0] = uuid;
            str[1] = imgurl;
            return str;
        }
        return null;
    }

    /**
     * 保存图片方法
     *
     * @param
     * @return
     */
    public String getImageattach(MeetingRecordPullDTO meetingRecordPullDTO) {
        ResultDTO resultDTO = new ResultDTO();
        // TODO Auto-generated method stub
        String enpenform_image = "";
        //获取配置图片地址
        String[] image_path = this.getImage_path();
        String image_pathAddr = image_path[1];//服务器项目目录地址
        String image_pathSerAddr = image_path[2];//图片访问地址
        String imgDirct = image_pathAddr + "/meetingroom";
        File f = new File(imgDirct);
        if (!f.exists()) {
            f.mkdirs();
            f.setWritable(true, false);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        String imgPath = imgDirct + "/" + meetingRecordPullDTO.getFile_type();


        //base64字符串保存为图片
        boolean headImg = FileProcess.GenerateImage(meetingRecordPullDTO.getFilestream(), imgPath);
        FileProcess.newlog("执行头像图片储存方法，储存照片地址：" + imgPath + " 方法返回：" + headImg);
        int resultls = 0;
        int mresult = 0;

        String imgurl = "/meetingroom/" + meetingRecordPullDTO.getFile_type();

        //ArrayList<HeadPortaitDTO> result = new ArrayList<HeadPortaitDTO>();

        if (headImg) {
            //插入头像表
            enpenform_image += "insert into attachment(attachment_id,attachment_addr,head_portrait_time,file_type,file_name) values ('" + uuid + "','" + imgurl + "','" + df.format(new Date()) + "','" + meetingRecordPullDTO.getFile_type() + "','" + meetingRecordPullDTO.getFile_name() + "')";
            // enpenform_image += "insert into file(file_id,file_addr,file_time,filegui_id,file_name) values ('" + uuid + "','" +imgurl+ "','" +df.format(new Date()) + "','" + dataDTO.getFilegui_id() + "','" + dataDTO.getFiletype() + "')";
            //执行sql
            resultls = addReportingTo(enpenform_image);
        }

        if (resultls != 0) {
            return uuid;
        }
        return null;
    }

    @Override
    public ResultDTO updateMeetingRcordInfo(MeetingRecordPullDTO meetingRecordPullDTO) {
        ResultDTO resultDTO = new ResultDTO();

        String QUERY = "";

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(new Date());

        //更新sql语句
        QUERY += "update meeting_record set update_time ='" + time + "'";

        if (null != meetingRecordPullDTO.getMeeting_name() && !"".equals(meetingRecordPullDTO.getMeeting_name())) {
            QUERY += ",meeting_name ='" + meetingRecordPullDTO.getMeeting_name() + "'";
        }
        if (null != meetingRecordPullDTO.getMeeting_desc() && !"".equals(meetingRecordPullDTO.getMeeting_desc())) {
            String html = replaceimage(meetingRecordPullDTO);
            QUERY += ",meeting_desc ='" + html + "'";
        }
        if (null != meetingRecordPullDTO.getMeeting_time() && !"".equals(meetingRecordPullDTO.getMeeting_time())) {
            QUERY += ",meeting_time ='" + meetingRecordPullDTO.getMeeting_time() + "'";
        }
        if (null != meetingRecordPullDTO.getMeeting_short_desc() && !"".equals(meetingRecordPullDTO.getMeeting_short_desc())) {
            QUERY += ",meeting_short_desc ='" + meetingRecordPullDTO.getMeeting_short_desc() + "'";
        }

        QUERY += " where meeting_record_id = '" + meetingRecordPullDTO.getMeeting_record_id() + "'";

        int result = this.addReportingTo(QUERY);
        // 判断SQl是否执行成功
        if (result != 0) {
            resultDTO.setStr(meetingRecordPullDTO.getMeeting_record_id());
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.update_success);
        } else {
            resultDTO.setStatus("90001");
        }
        return resultDTO;
    }

    @Override
    public ResultDTO deleteMeetingRcordInfo(MeetingRecordPullDTO meetingRecordPullDTO) {
        //删除之前查询是否有记录
        String sql = "select count(1) from meeting_record where meeting_record_id ='" + meetingRecordPullDTO.getMeeting_record_id() + "'";

        String existName = getReportingToOne(sql);

        int result = 0;

        ResultDTO resultDTO = new ResultDTO();

        if (!existName.equals("0")) {

            String QUERY = "";
            QUERY += "delete from meeting_record where meeting_record_id='" + meetingRecordPullDTO.getMeeting_record_id() + "'";

            result = this.addReportingTo(QUERY);
        }

        if (result != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.delete_success);

        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.delete_fail);
        }
        return resultDTO;
    }
}
